<template>
    <TheElDialog :title="title" :visible.sync="centerDialogVisible" @close="handleCenterDialogClose" v-bind="$attrs">
        <el-form
            @submit.native.prevent
            ref="formRule"
            :model="form"
            :rules="rules"
            :label-width="isMobile ? '80px' : '120px'"
        >
            <el-form-item prop="licensePlate" label="车牌号">
                <el-input v-model="form.licensePlate" placeholder="请填写车牌号，例如：粤B1Z333"></el-input>
            </el-form-item>
            <el-form-item prop="brandType" label="品牌型号">
                <el-input v-model="form.brandType" placeholder="请填写品牌型号"></el-input>
            </el-form-item>
            <el-form-item prop="driver" label="驾驶员">
                <el-select v-model="form.driver" filterable clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in optionsPersons" :key="item._id" :label="item.name" :value="item._id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="price" label="车辆价格">
                <el-input
                    type="number"
                    @mousewheel.native.prevent
                    @DOMMouseScroll.native.prevent
                    v-model="form.price"
                    placeholder="请填写车辆价格"
                ></el-input>
            </el-form-item>
            <el-form-item prop="bodyColor" label="车身颜色">
                <el-input v-model="form.bodyColor" placeholder="请填写车身颜色"></el-input>
            </el-form-item>
            <el-form-item prop="mileage" label="行驶里程">
                <el-input
                    type="number"
                    @mousewheel.native.prevent
                    @DOMMouseScroll.native.prevent
                    v-model="form.mileage"
                    placeholder="请填写行驶里程"
                >
                    <span slot="suffix" class="el-input__icon">公里</span>
                </el-input>
            </el-form-item>
            <el-form-item prop="engineNumber" label="发动机号">
                <el-input v-model="form.engineNumber" placeholder="请填写发动机号"></el-input>
            </el-form-item>
            <el-form-item prop="frameNumber" label="车架号">
                <el-input v-model="form.frameNumber" placeholder="请填写车架号"></el-input>
            </el-form-item>
            <el-form-item prop="manufacturer" label="生产厂家">
                <el-input v-model="form.manufacturer" placeholder="请填写生产厂家"></el-input>
            </el-form-item>
            <el-form-item prop="dateOfProduction" label="出厂日期">
                <el-date-picker
                    type="date"
                    placeholder="选择日期"
                    format="yyyy/MM/dd"
                    prefix-icon="false"
                    v-model="form.dateOfProduction"
                    :clearable="true"
                    class="form-the-datepicker"
                    style="width: 100%;"
                ></el-date-picker>
            </el-form-item>
            <el-form-item prop="dateAnnualInspectionExpiration" label="年检到期">
                <el-date-picker
                    type="date"
                    placeholder="选择日期"
                    format="yyyy/MM/dd"
                    prefix-icon="false"
                    v-model="form.dateAnnualInspectionExpiration"
                    :clearable="true"
                    class="form-the-datepicker"
                    style="width: 100%;"
                ></el-date-picker>
            </el-form-item>
            <el-form-item prop="dateExpirationOfInsurance" label="保险到期">
                <el-date-picker
                    type="date"
                    placeholder="选择日期"
                    format="yyyy/MM/dd"
                    prefix-icon="false"
                    v-model="form.dateExpirationOfInsurance"
                    :clearable="true"
                    class="form-the-datepicker"
                    style="width: 100%;"
                    >></el-date-picker
                >
            </el-form-item>
            <el-form-item prop="emissionLevel" label="排放等级">
                <el-input v-model="form.emissionLevel" placeholder="请填写排放等级"></el-input>
            </el-form-item>
            <el-form-item prop="status" label="车辆状态">
                <el-select v-model="form.status" filterable clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in CAR_STATUS" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="ownership" label="车辆归属">
                <el-select v-model="form.ownership" filterable clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in CAR_OWNERSHIPS" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="remark" label="备注">
                <el-input
                    :disabled="isDetail"
                    :show-word-limit="form.remark ? form.remark && form.remark.length > 190 : false"
                    :maxlength="200"
                    type="textarea"
                    v-model="form.remark"
                    placeholder="请填写备注"
                ></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button :disabled="centerDialogLoading" @click="centerDialogVisible = false">取 消</el-button>
            <el-button
                :disabled="isDetail"
                :loading="centerDialogLoading"
                type="primary"
                @click="handleSubmit('formRule')"
                >确 定</el-button
            >
        </span>
    </TheElDialog>
</template>
<script>
import {postApiList, putApiList} from '@/api/car';
import getRules from '@/views/system/car/getRules';
import {CAR_OWNERSHIPS, CAR_STATUS} from '@/views/system/car/constant';
export default {
    name: 'center-dialog',
    props: {
        title: {
            type: String,
            default: ''
        },
        visible: {
            type: Boolean,
            default: false
        },
        dataSource: {
            type: Object,
            required: true
        },
        optionsPersons: {
            type: Array,
            default: () => [],
            required: true
        }
    },
    components: {},
    data() {
        return {
            CAR_OWNERSHIPS,
            CAR_STATUS,
            // 新建弹窗 提交表单中
            centerDialogLoading: false,
            inputStyle: {width: '320px'},
            // 新建表单
            form: {
                id: undefined,
                licensePlate: undefined,
                brandType: undefined,
                driver: undefined,
                price: undefined,
                bodyColor: undefined,
                mileage: undefined,
                engineNumber: undefined,
                frameNumber: undefined,
                manufacturer: undefined,
                dateOfProduction: undefined,
                dateAnnualInspectionExpiration: undefined,
                dateExpirationOfInsurance: undefined,
                emissionLevel: undefined,
                status: undefined,
                ownership: undefined,
                remark: undefined
            },
            rules: getRules()
        };
    },
    computed: {
        isMobile() {
            return this.$store.getters['app/isMobile'];
        },
        isDetail() {
            return typeof this.title === 'string' && this.title.includes('查看');
        },
        centerDialogVisible: {
            get() {
                return this.visible;
            },
            set(val) {
                this.$emit('update:visible', val);
            }
        }
    },
    watch: {
        dataSource: {
            handler(val) {
                this.form = {...this.form, ...val};
                this.$nextTick(() => {
                    this.$refs.formRule && this.$refs.formRule.clearValidate();
                });
            },
            immediate: true
        }
    },
    methods: {
        // 提交表单
        handleSubmit(formName) {
            this.$refs[formName].validate((valid, fields) => {
                if (valid) {
                    const form = this.form;
                    const newItem = {
                        _id: form._id,
                        licensePlate: form.licensePlate,
                        brandType: form.brandType,
                        driver: form.driver,
                        price: form.price - 0,
                        bodyColor: form.bodyColor,
                        mileage: form.mileage - 0,
                        engineNumber: form.engineNumber,
                        frameNumber: form.frameNumber,
                        manufacturer: form.manufacturer,
                        dateOfProduction: form.dateOfProduction,
                        dateAnnualInspectionExpiration: form.dateAnnualInspectionExpiration,
                        dateExpirationOfInsurance: form.dateExpirationOfInsurance,
                        emissionLevel: form.emissionLevel,
                        status: form.status,
                        ownership: form.ownership,
                        remark: form.remark
                    };

                    if (this.title && this.title.includes('添加')) {
                        this.onCreate(newItem);
                    }
                    if (this.title && this.title.includes('编辑')) {
                        this.onPutData(newItem);
                    }
                } else {
                    const first = Object.keys(fields)[0];
                    const items = fields[first] || [];
                    const {message} = items[0] || {};
                    this.$message({showClose: true, type: 'error', message});
                    return false;
                }
            });
        },
        // 创建角色
        onCreate(newItem) {
            this.centerDialogLoading = true;
            postApiList(newItem)
                .then(({data: res}) => {
                    if (res.status === 201) {
                        this.$message({showClose: true, type: 'success', message: '创建成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    const data = error.response && error.response.data;

                    if (data && data.error) {
                        this.$message({showClose: true, type: 'error', message: data.error});
                    } else {
                        this.$message({showClose: true, type: 'error', message: '创建失败'});
                    }
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // 更新
        onPutData(newItem) {
            this.centerDialogLoading = true;
            putApiList(newItem._id, newItem)
                .then(({data: res}) => {
                    if (res.status === 204) {
                        this.$message({showClose: true, type: 'success', message: '更新成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    this.$message({showClose: true, type: 'error', message: error});
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // dialog 关闭
        handleCenterDialogClose() {
            // 关闭
            this.$emit('close');
            this.form = {
                id: undefined,
                datetime: '',
                store: undefined,
                order: undefined,
                depot: '',
                remark: ''
            };
        }
    }
};
</script>

<style lang="scss" scoped>
::v-deep {
    .el-form {
        display: flex;
        flex-flow: row wrap;
        .el-form-item {
            flex: 0 0 50%;
        }
    }
}
</style>
